package com.rico.gallery.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.rico.gallery.R;
import com.rico.gallery.device.DeviceInfo;
import com.uuzuche.lib_zxing.activity.CodeUtils;

public class QRCodeFragment extends Fragment {
    private View view;
    private ImageView iv_qr_code;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if(view==null){
            view=inflater.inflate(R.layout.qrcode, container, false);
            iv_qr_code=(ImageView) view.findViewById(R.id.img_qrcode);
            String content =getRQCodeContent();
            Bitmap bitmap = CodeUtils.createImage(content, 400, 400, null);
            iv_qr_code.setImageBitmap(bitmap);
            iv_qr_code.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String content =getRQCodeContent();
                    Bitmap bitmap = CodeUtils.createImage(content, 400, 400, null);
                    iv_qr_code.setImageBitmap(bitmap);
                }
            });

        }
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ViewGroup p = (ViewGroup) view.getParent();
        if(p!=null){
            p.removeView(view);
        }
    }


    public String getRQCodeContent(){
        DeviceInfo device=new DeviceInfo();
        String serialNumber = android.os.Build.SERIAL;
        device.setDeviceId(serialNumber);
        device.setLocalIP(getIp());
        device.setLocalPort(10088);
        String json= JSON.toJSONString(device);
        System.out.println("json :"+json);
        return json;
    }

    private String getIp(){
        WifiManager wm=(WifiManager)this.getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //检查Wifi状态
        if(!wm.isWifiEnabled())
            wm.setWifiEnabled(true);
        WifiInfo wi=wm.getConnectionInfo();
        //获取32位整型IP地址
        int ipAdd=wi.getIpAddress();
        //把整型地址转换成“*.*.*.*”地址
        String ip=intToIp(ipAdd);
        return ip;
    }
    private String intToIp(int i) {
        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

}
